<template>
  <el-form :model="forms" label-width="40px">
    <el-form-item label="地市">
      <el-row>
        <el-col :span="!onlyCity ? 12 : 24">
          <el-select @change="changeOptions()" v-model="forms.cityCode" clearable placeholder="请选择市">
            <el-option v-for="item in cityOption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-col>
        <el-col :span="12" v-if="!onlyCity">
          <el-select v-model="forms.countyCode" clearable placeholder="请选择县">
            <el-option v-for="item in origenOption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-col>
      </el-row>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {ref, reactive, defineEmits, defineProps, computed, watch, toRefs} from "vue"
import {getCityName} from "@/api/business/business.js"
import {Codes} from "./cityConfig.d"
const props = defineProps({
  form: {
    type: Object,
    required: true,
    default: () => {},
  },
  onlyCity: {
    type: Boolean,
    required: false,
    default: false,
  },
})
//form更新到页面
let emit = defineEmits(["update:form"])
//city循环
let cityOption = ref(null)
//区域循环
let origenOption = ref(null)
//form接收
let forms = props.form
// 监听接收之后的表单变化（城市和区划的联动关系；并响应到页面）
watch(forms, val => {
  if (val.cityCode == "") {
    val.countyCode = ""
  } else {
    countys(val.cityCode)
  }

  emit("update:form", val)
})
//获取城市
async function citys() {
  let {data: cityOptionOld} = await getCityName({parent: Codes.cityCode})
  cityOption.value = cityOptionOld
}
//获取县区
async function countys(e: any) {
  let {data: origenOptionOld} = await getCityName({parent: e})
  origenOption.value = origenOptionOld
}
//只要城市变化县区清空
function changeOptions() {
  forms.countyCode = ""
}
citys()
</script>
<style lang="scss" scoped></style>
